<?php
namespace app\applet\controller;

use app\applet\model\Applet as AppletModel;
use app\applet\model\Apply as ApplyModel;
use app\applet\model\Config;
use hema\wechat\Driver;
use think\facade\View;


/**
 * 微信小程序管理
 */
class Wxapp extends Controller
{
	/**
     * 小程序设置
     */
    public function index()
    {
        $model = AppletModel::get($this->applet_id);
        $apply = [];
        $infor = [];
        $wx = new Driver;
        $url = $wx->authUrl($this->applet_id,2);//获取授权页面地址
        if($model['status']['value'] == 0){
        	$apply = ApplyModel::getApply(['apply_mode' => 10]);//注册信息
        }else{
        	$config = Config::detail();
        	$model['serve_domain'] = $config['api_domain'];//获取最新服务器域名列表
        	//获取已授权小程序设置信息
        	if(!$result = $wx->getInfor($this->applet_id)){
        	    return $this->renderError($wx->getError());
        	}
        	$infor = $result;
        }
        if (!$this->request->isAjax()) {
	        return View::fetch('index', compact('model','infor','apply','url'));
        }
        if ($model->edit($this->postData('data'))){
        	return $this->renderSuccess('更新成功');
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }

    /**
     * 生成体验版二维码
     */
	public function testCode()
	{
		$wx = new Driver;
		$result = $wx->getTestCode($this->applet_id);
		$path = 'temp';
		if(!file_exists($path)){
			mkdir($path,0777,true);
		}
		file_put_contents($path . '/test_code_'. $this->applet_id .'.png',$result); //获取的二维码数据存储到指定的文件
		return redirect('/' . $path . '/test_code_'. $this->applet_id .'.png');
	}

	/**
     * 设置头像
     */
    public function sethead()
    {
        $model = AppletModel::get($this->applet_id);
        if (!$this->request->isAjax()) {
			return View::fetch('sethead', compact('model'));
        }
        $data = $this->postData('data');
        //判断是否更换了头像
        if($data['head_img'] != $model['head_img']){ 
			if(empty($data['head_img'])){
				return $this->renderError('请选择一个头像图片');
			}
			$wx = new Driver;
			//上传临时素材
			if(!$media_id = $wx->upTempMaterial($data['head_img'],$this->applet_id)){
				return $this->renderError($wx->getError());
			}
			//设置头像
			if(!$wx->modifyHeadImage($media_id,$this->applet_id)){
				return $this->renderError($wx->getError());
			}
			if (!$model->save($data)){
				return $this->renderError('设置失败');
			}
		}
        return $this->renderSuccess('设置成功', url('wxapp/index'));
    }

    /**
     * 同步小程序信息
     */
    public function synchronization($app_id)
    {
    	$wx = new Driver;
		//获取授权应用的帐号基本信息
		if(!$result = $wx->getAppInfo($app_id)){
		    return $this->renderError($wx->getError());
		}
		$app = $result['authorizer_info'];
		$applet = AppletModel::get($this->applet_id);
		$api_domain = implode(';',$app['MiniProgramInfo']['network']['RequestDomain']);
		$api_domain = str_replace('http://','',$api_domain);
		$api_domain = str_replace('https://','',$api_domain);
		$applet->save([
			'app_name' => isset($app['nick_name'])?$app['nick_name']:'',	//昵称
			'head_img' => isset($app['head_img'])?$app['head_img']:'',		//头像
			'qrcode_url' => isset($app['qrcode_url'])?$app['qrcode_url']:'',	//二维码
			'user_name' => $app['user_name'],					//原始ID
			'principal_name' => $app['principal_name'],			//主体名称
			'signature' => isset($app['signature'])?$app['signature']:'',	//账号介绍		
			'api_domain' => $api_domain,	//账号介绍		
		]);
		return $this->renderSuccess('同步成功', url('wxapp/index'));
	}

}
